<?php
global $socket;

if (!ModuleController::hasModule("initialisation")) ModuleController::loadModule("initialisation");
if (!ModuleController::hasModule("ircmessaging")) ModuleController::loadModule("ircmessaging");

switch ($aEvent->type)
{
	case Module::INITIALIZE_MODULE:
		Events::dispatchEvent(new Event(Initialisation::INITIALIZE));

		if ($socket = fsockopen(Configuration::get("server"), Configuration::get("port")))
		{
			Debug::log("Opened socket to " . Configuration::get("server") . ":" . Configuration::get("port"), Debug::INFO);
			
			Events::dispatchEvent(new Event(Message::INIT_USER));
			Events::dispatchEvent(new Event(Message::INIT_NICK));
			Events::addEventListener(MessageEvent::MESSAGE, "irccore");
			
			while($socket != null && !feof($socket))
			{
				Events::dispatchEvent(new Event(Message::PARSE, trim(fgets($socket, 4096))));
			}			
		}
		else
		{
			Debug::log("Failed to open a socket to " . Configuration::get("server") . ":" . Configuration::get("port"), Debug::ERROR);
		}
		break;
		
	case MessageEvent::MESSAGE:
		if ($aEvent->from == "" && $aEvent->to == "" && strtoupper($aEvent->command) == "PING")
		{
			Events::dispatchEvent(new Event(Message::SENDPONG, implode(' ', $aEvent->params)));
		}
		break;
		
	case Module::UNLOAD_MODULE:
		Events::removeEventListener(MessageEvent::MESSAGE, "irccore");
		
		if (isset($socket))
		{
			fclose($socket);
			Debug::log("Closed socket to " . Configuration::get("server") . ":" . Configuration::get("port"), Debug::INFO);
		}
		break;
	
	default:
		break;
}
?>